﻿$(document).ready(function() {

	$.namespace("currentmonth", {
		inherited: true,

		InitialiseControl: function() {
			$.fn.currentmonth.LoadSpendingGrid();
		},

		LoadSpendingGrid: function() {

			var mthCatCombo = new Ext.form.ComboBox({
				store: new Ext.data.JsonStore({
					fields: ['MthCategoryId', 'CategoryName'],
					data: $.fn.global.CurrentMonthCategories()
				}),
				displayField: 'CategoryName',
				valueField: 'MthCategoryId',
				typeAhead: true,
				mode: 'local',
				triggerAction: 'all'
				//lazyRender: true,
			});

			/* Define the grid that will display the support adding the  */
			function SpendingGrid() {
				//helper functions
				function formatDate(value) {
					return value ? value.dateFormat('d / M / Y') : '';
				}

				//proxy
				var proxy = new Ext.data.HttpProxy({
					url: 'Data/Spendings.aspx'
				});

				//reader
				var reader = new Ext.data.JsonReader({
					root: 'Data',
					totalProperty: 'Count',
					idProperty: 'SpendingId',
					fields: [
						{ name: 'SpendingId', type: 'int' },
						{ name: 'Description', type: 'string', allowBlank: false },
						{ name: 'DateSpent', type: 'date', dateFormat: 'M$', allowBlank: false },
						{ name: 'Amount', type: 'float', allowBlank: false },
						{ name: 'MthCategoryId', type: 'int', allowBlank: false },
						{ name: 'Timestamp', type: 'date', dateFormat: 'M$' },
						{ name: 'Version', type: 'auto' }
					]
				});

				//writer
				var writer = new Ext.data.JsonWriter({
					encode: true,   // <-- don't return encoded JSON -- causes Ext.Ajax#request to send data using jsonData config rather than HTTP params
					writeAllFields: true
				});

				//store
				var store = new Ext.data.Store({
					id: 'dsMths',
					proxy: proxy,
					reader: reader,
					writer: writer,    // <-- plug a DataWriter into the store just as you would a Reader
					sortInfo: {
						field: 'DateSpent',
						direction: 'DESC'
					},
					listeners: {
						'update': function(store, record, operation) {
							store.commitChanges();

							var monthSummaryGrid = Ext.getCmp('MonthSummaryGrid');
							monthSummaryGrid.getStore().load();
						}
					}
				});


				//colModel
				var colModel = new Ext.grid.ColumnModel({
					defaults: {
						sortable: true
					},
					columns: [
						{ header: 'Date Spent', dataIndex: 'DateSpent', renderer: formatDate,
							editor: new Ext.form.DateField({
								format: 'd / M / y',
								minValue: '01/01/09'
							})
						},
						{ header: 'Amount', dataIndex: 'Amount', align: 'right', xtype: 'numbercolumn', format: '$0,0.00', editor: new Ext.form.NumberField({}) },
						{ header: 'Description', dataIndex: 'Description', editor: new Ext.form.TextField({}) },
						{ header: 'Month Category', dataIndex: 'MthCategoryId', editor: mthCatCombo, renderer: $.fn.global.ComboRenderer(mthCatCombo) }
					]
				});

				//buttons
				//row-editor
				var editor = new Ext.ux.grid.RowEditor({
					saveText: 'Update'
				});

				var addBtn = new Ext.Button({
					id: 'addBtn',
					text: 'Add',
					iconCls: 'silk-add',
					handler: function(btn, ev) {
						var currentMonthMsg = "";
						var currentMonthCategoriesMsg = "";
						
						if ($.fn.global.CurrentMonth() == null) { currentMonthMsg = 'You need to create a Month entry to track spendings!\n'; }
						if ($.fn.global.CurrentMonthCategories() == null) { currentMonthCategoriesMsg = 'You need to set the Categories to track for this Month!\n'; }

						if (currentMonthMsg.length > 0 || currentMonthCategoriesMsg.length > 0) {
							if (confirm(currentMonthMsg + currentMonthCategoriesMsg + 'Would you like to create it/them now?')) {
								var appTabs = Ext.getCmp('apptabs');
								appTabs.setActiveTab('tabm');
							}
						}
						else {
							var u = new grid.store.recordType({
								DateSpent: new Date(),
								Description: '',
								Amount: '',
								MthCategoryId: ''
							});
							editor.stopEditing();
							grid.store.insert(0, u);
							editor.startEditing(0);
						}
					}
				});

				var refreshBtn = new Ext.Button({
					id: 'refreshBtn',
					text: 'Refresh',
					iconCls: 'silk-table-refresh',
					handler: function(btn, ev) {
						grid.getStore().rejectChanges();
						grid.getStore().reload();
					}
				});

				//grid
				var grid = new Ext.grid.GridPanel({
					id: 'SpendingsGrid',
					iconCls: 'icon-grid',
					frame: true,
					title: 'Spendings For The Month',
					loadMask: true,
					autoScroll: true,
					height: 300,
					store: store,
					plugins: [editor],
					colModel: colModel,
					viewConfig: {
						forceFit: true
					},
					tbar: [addBtn, '-', '->', '-', refreshBtn]
				});

				//return the grid...
				return grid;
			}


			/* Define the panel that will house the Spending grid and the Mth Category summary */
			function CreatePanel() {
				var tabContent = $("#CurrentMonthContainer").children(".TabContent");

				var currentMonthPanel = new Ext.Panel({
					id: 'currentMonthPanel',
					//title: 'Panel Title',
					layout: 'column',
					padding: 0,
					bodyBorder: false,
					border: false,
					items: [{
						id: 'regSpendingsGrid',
						border: false,
						padding: '0px 5px 0px 0px',
						columnWidth: 0.60,
						//verticalAlign: 'top',
						items: [SpendingGrid()]
						//html: '<p>This is some short content.</p>'*/
					}, {
						id: 'regMthCategorySummary',
						border: false,
						padding: '0px 0px 0px 5px',
						columnWidth: 0.40,
						//verticalAlign: 'top',
						items: [$.fn.global.SummaryGrid(new Date(), true)]
						//html: '<p>This is some longer content.</p><p>This is some longer content.</p><p>This is some longer content.</p><p>This is some longer content.</p><p>This is some longer content.</p><p>This is some longer content.</p>'
}]
					});

					currentMonthPanel.render(tabContent[0]);

					var spendingGrid = Ext.getCmp('SpendingsGrid');
					spendingGrid.getStore().load();

					var monthSummaryGrid = Ext.getCmp('MonthSummaryGrid');
					monthSummaryGrid.getStore().load();

				};

				//draw the page	
				CreatePanel();
			}
		});
	});